package com.example.areaclean;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.example.areaclean.dao.User;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class man_select extends AppCompatActivity {
    private Button upload,takePic;
    private ImageView imgView;
    private String score;
    private String text;
    private File phoneFile;
    RequestQueue queue;
    private String c_no1;
    private String man_time;
    private SharedPreferences pref;
    private SharedPreferences.Editor editor;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        setContentView(R.layout.activity_man_select);
        Intent intent =getIntent();
        c_no1=intent.getStringExtra("c_no1");
        Log.d("qqqqqqq", c_no1);


        queue = Volley.newRequestQueue(getApplicationContext());
        upload = (Button)findViewById(R.id.btn_submit);
        takePic = (Button)findViewById(R.id.addimg);
        imgView = (ImageView)findViewById(R.id.s_img);

        final EditText edit_score=findViewById(R.id.edit_score);
        final EditText editText =findViewById(R.id.addtext);

        //分数下拉列表
        Spinner score_spin=(Spinner) findViewById(R.id.score_spin);
        final String[] scoreItems = getResources().getStringArray(R.array.score);
        ArrayAdapter<String>adapter = new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,scoreItems);
        score_spin.setAdapter(adapter);


        score_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                score=scoreItems[i];
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


        takePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent iimg =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                phoneFile =new File(Environment.getExternalStorageDirectory().getAbsoluteFile()
                        +"/"+getTime()+".jpg");
                iimg.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(phoneFile));
                startActivityForResult(iimg,1);
            }
        });
        upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String s = imageToBase64(phoneFile.getAbsolutePath());
                text=editText.getText().toString();
                Log.d("base64",s);
                man_time=getTime();
                pref = getSharedPreferences("data",MODE_PRIVATE);
                String sno;
                sno=pref.getString("userNo","");
                jsonRequest("img",s,score,text,c_no1,man_time,sno);

//                jsonRequest("img_upload",s);
            }
        });
    }

    private String getTime(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        String str = format.format(date);
        return str;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1)
        {//如果等于1代表传递的是一个图片
            Bitmap bitmap = BitmapFactory.decodeFile(phoneFile.getAbsolutePath());
            Log.d("base64",phoneFile.getAbsolutePath());
            imgView.setImageBitmap(bitmap);
        }
    }

    public static String imageToBase64(String path){
        if(TextUtils.isEmpty(path)){
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try{
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data,Base64.NO_WRAP);
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(null !=is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }

    public void jsonRequest(String aim,final String img,String man_score,String man_text,String c_no,String man_time,String sno){//通过组长编号查询教室
        String url ="http://192.168.31.32/tp/public/index.php/api/man_qdb";

        HashMap<String, String> params = new HashMap<String ,String>();
        params.put("forwhat",aim);
        params.put("img",img);
        params.put("score",man_score);
        params.put("man_text",man_text);
        params.put("c_no",c_no);
        params.put("time",man_time);
        params.put("s_no",sno);
        JSONObject jsonObject =new JSONObject(params);
        Log.d("base64",jsonObject.toString());
        Log.d("RRRRR", man_score+" "+man_text+" "+c_no+" "+man_time);
        JsonObjectRequest jsonObjectRequest =new JsonObjectRequest(Request.Method.POST, url, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        String s = "";
                        try {
                            s = jsonObject.getString("man_qdb");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if(s.equals("successful")){
                            Toast.makeText(man_select.this,"签到成功",Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(man_select.this,"签到失败",Toast.LENGTH_SHORT).show();
                        }

                        Log.d("base64",s);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d("base64","Error"+volleyError);
                    }

                });
        queue.add(jsonObjectRequest);
    }

}
